package com.zhang.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.config.Result;
import com.zhang.pojo.Article;
import com.zhang.service.HtmlParse;
import com.zhang.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ArticleMapperImpl {

    @Resource
    ArticleMapper articleMapper;

    IdUtil idUtil = new IdUtil();
    Logger logger = LoggerFactory.getLogger(getClass());
    String list = "https://www.czu.cn/6/list";

    /**
     * 模糊查询
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    public Result<?> fuzzySearch(Integer pageNum, Integer pageSize, String search){

        logger.info("【操作】模糊查询");
        LambdaQueryWrapper<Article> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(search)){
            wrapper.like(Article::getArticleTitle, search)
                    .select(Article.class,i -> !i.getColumn().equals("article_content")); //不查询指定的列
        }
        Page<Article> articlePage = articleMapper.selectPage(new Page<>(pageNum, pageSize),wrapper);
        return Result.success(articlePage);
    }

    /**
     * 根据时间分页查询
     * @param pageNum
     * @param pageSize
     * @param time
     * @return
     */
    public Result<?> searchByTime(Integer pageNum,Integer pageSize, int time){ //显示最近X天的数据，返回json字符串

        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        logger.info("【操作】根据时间分页查询");

        Date date; Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        date=cal.getTime();String end = sdf.format(date);
        cal.add(Calendar.HOUR,-time*24);
        date=cal.getTime();String begin = sdf.format(date);

        //查询最近x天的
        if (StringUtils.isNotBlank(begin)&&StringUtils.isNotBlank(end)){
            wrapper.between("article_pubtime", begin, end).select(Article.class,i -> !i.getColumn().equals("article_content")); //不查询指定的列
        }
        //排序
        wrapper.orderByDesc("article_pubtime");

        Page<Article> articlePage = articleMapper.selectPage(new Page<>(pageNum, pageSize),wrapper);
        return Result.success(articlePage);
    }

    /**
     * 根据id查询
     * @return
     */
    public Result<?> searchByID(Long articleId) {
        //查询最近x天的
        logger.info("【操作】根据id查询");
        Article article = articleMapper.selectById(articleId);
        return Result.success(article);
    }

    /**
     * 每日更新，判断是否已经存在
     * @return
     * @throws Exception
     */
    @Scheduled(cron = "0 0 * ? * *") //cron表达式：每天的凌晨4点执行一次 错误的表达式 * * */4 * * ?
    public Result<?> updateArticle() throws Exception {
        Article article;
        List<Article> articleList = new ArrayList<>();

        logger.info("【操作】每日更新");

        for (int i=1; i<3; i++){ //获取前两页li标签中的链接
            for (int j=1; j<15; j++) {
                article = new HtmlParse().parseHtml(list + i + ".htm", j);

                if (article!=null){
                    LambdaQueryWrapper<Article> wrapper = Wrappers.lambdaQuery();
                    wrapper.eq(Article::getArticleTitle, article.getArticleTitle());
                    if (articleMapper.selectList(wrapper).size()!=0){ //不为零，说明已经存在
                        logger.info("【错误】已经存在该公告");
                    }else {
                        article.setArticleId(idUtil.getID());
                        logger.info("【新公告】" + article.getArticleTitle());
                        articleList.add(article);
                    }
                }else {
                    logger.info("【错误】链接异常");
                }
            }
        }

        if (articleList.size()>0){
            articleMapper.listInsert(articleList) ; //从新到旧挨个插入
        }

        logger.info("【成功】更新完成");
        return Result.success();
    }


    /**
     * 初始化数据库
     * @return
     */
    @Scheduled(cron = "0 0 3 L * ?") //cron表达式：每个月最后一天的3点更新一次数据库执行一次
    public Result<?> insertFirst() {
        List<Article> articleList = new ArrayList<>();
        Article article;
        articleMapper.deleteAllArticle(); //请空表中的所有数据，并让主字段从1开始自增
        logger.info("【操作】初始化数据库");

        for (int i=1; i<20; i++){
            for (int j = 1; j < 15; j++) {
                try {
                    logger.info("正在更新...");
                    article = new HtmlParse().parseHtml(list + i + ".htm", j);

                    if (article!=null){
                        System.out.println("文章标题：" + article.getArticleTitle());
                        article.setArticleId(idUtil.getID());
                        articleList.add(article);
                        logger.info("【新公告】" + article.getArticleTitle());
                    }
                }catch (Exception e2){
                    logger.info("【错误】初始化数据库时链接异常");
                }
            }
        }
        if (articleList.size()>0){
            articleMapper.listInsert(articleList) ; //从新到旧挨个插入
        }
        logger.info("【成功】批量插入");
        return Result.success();
    }
}